const state = {
  tabs: JSON.parse(localStorage.getItem('tabs')) || [] // 标签页
}

const getters = {
  getTabs: state => state.tabs
}

const mutations = {
  // 新建标签页
  NEW_TABS: (state, data) => {
    // 判断已展开标签页或首页
    if (state.tabs.some(name => name.path === data) || data === '/') {
      return
    }
    const path = `/${data.split('/')[1]}` // 获取子菜单 (key)
    const navMenu = JSON.parse(localStorage.getItem('menu')) // 导航菜单
    const childMenu = navMenu.filter(name => name.path === path)[0].children // 获取子菜单
    const tabs = childMenu.filter(tab => tab.path === data)[0] // 当前标签页
    state.tabs.push({name: tabs.name, path: tabs.path}) // 添加当前标签页
    localStorage.setItem('tabs', JSON.stringify(state.tabs))
  },
  // 关闭标签页
  CLOSE_TABS: (state, data) => {
    if (data === 'closeAllTabs') {
      state.tabs = [] // 关闭所有标签页
      localStorage.removeItem('tabs')
      return
    }
    state.tabs = state.tabs.filter(tab => {
      if (data[0] === 'closeTab') {
        return tab.path !== data[1] // 关闭当前标签页
      }
      return tab.path === data[1] // 关闭其它标签页
    })
    localStorage.setItem('tabs', JSON.stringify(state.tabs))
  }
}

export default {state, getters, mutations}
